package com.weir.resilience4j.consumer;

import java.time.Duration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
import io.github.resilience4j.retry.annotation.Retry;
import io.vavr.control.Try;

@Service
public class HelloService2 {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    CircuitBreakerRegistry circuitBreakerRegistry;
//断路器
    public String hello2(String name) {
	    CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
	            .failureRateThreshold(50)
	            .waitDurationInOpenState(Duration.ofMillis(1000))
	            .permittedNumberOfCallsInHalfOpenState(20)
//	            .ringBufferSizeInHalfOpenState(20)
//	            .ringBufferSizeInClosedState(20)
	            .build();
	    io.github.resilience4j.circuitbreaker.CircuitBreaker circuitBreaker = circuitBreakerRegistry.circuitBreaker("retryBackendB", circuitBreakerConfig);
	    Try<String> supplier = Try.ofSupplier(io.github.resilience4j.circuitbreaker.CircuitBreaker
	            .decorateSupplier(circuitBreaker,
	                    () -> restTemplate.getForObject("http://localhost:9999/hell?name={1}", String.class, name)))
	            .recover(Exception.class, "有异常，访问失败!");
	    return supplier.get();
	}


}
